package com.example.pfe_copie_finale;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.pfe_copie_finale.R;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

public class BonLivraison1 extends Activity implements
		AdapterView.OnItemSelectedListener, OnClickListener {
	 // Progress Dialog
    private ProgressDialog pDialog;
    
 // Creating JSON Parser object
    jsonParser jParser = new jsonParser();
 
    ArrayList<HashMap<String, String>> departementList;
 
    // url to get all products list
    private static String url_all_departements = "http://10.0.2.2/getAllDepartement";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_depart = "departements";
    private static final String TAG_PID = "id";
    private static final String TAG_NAME = "libelle";
    private List<String> array_spinner=new ArrayList<String>();
      // products JSONArray
        JSONArray departements = null;
	
	private Spinner spinner; 
	private EditText pickDate;
	private EditText pickDate1;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mYear1;
	private int mMonth1;
	private int mDay1;
	static final int DATE_DIALOG_ID1 = 1;
	static final int DATE_DIALOG_ID2 = 2;
	Button Suivant = null;
//	TextView selection;
//	String[] items = { "thisjjj", "is", "a", "really", 
//			"really2", "really3",
//			"really4", "really5", "silly", "list" };
//
//	@Override
//	

	

	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bon_livraison1);
		Suivant= (Button)findViewById(R.id.Suivant);
		spinner = (Spinner) findViewById(R.id.spinner);
		Suivant.setOnClickListener(this);
		
	
		
		pickDate = (EditText) findViewById(R.id.datep);
		pickDate1 = (EditText) findViewById(R.id.datel);
		
//		selection = (TextView) findViewById(R.id.selection);
//	
			
		
//
//		Spinner spin = (Spinner) findViewById(R.id.spinner);
//		spin.setOnItemSelectedListener(this);
//
//		ArrayAdapter aa = new ArrayAdapter(
//				this,
//				android.R.layout.simple_spinner_item, 
//				items);
//
//		aa.setDropDownViewResource(
//
//				android.R.layout.simple_spinner_dropdown_item);
//		spin.setAdapter(aa);
//		
//		
		
		// Hashmap for ListView
	       departementList = new ArrayList<HashMap<String, String>>();
	       // Loading products in Background Thread
	      
	        new LoadDepartements().execute();
	        array_spinner.add("choisir departement");
	        ArrayAdapter adapter = new ArrayAdapter(BonLivraison1.this,android.R.layout.simple_spinner_item, array_spinner);
	        spinner.setAdapter(adapter);
		
		
		pickDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
			showDialog(DATE_DIALOG_ID1);
			}
			});
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			updateDisplay(DATE_DIALOG_ID1);
			
		
		
		pickDate1.setOnClickListener(new View.OnClickListener() {

		public void onClick(View v) {
		showDialog(DATE_DIALOG_ID2);
		}
		});
		final Calendar c1 = Calendar.getInstance();
		mYear1 = c1.get(Calendar.YEAR);
		mMonth1 = c1.get(Calendar.MONTH);

		mDay1 = c1.get(Calendar.DAY_OF_MONTH);
		updateDisplay(DATE_DIALOG_ID2);
		
		
		
	
	}
	
	
	
	
	
	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
	}

	public void onNothingSelected(AdapterView<?> parent) {}
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID1:
		    return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
		case DATE_DIALOG_ID2:
			return new DatePickerDialog(this,mDateSetListener1,mYear1, mMonth1, mDay1);
		}
		return null;
		}
		protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID1 :
		((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);break;

		case DATE_DIALOG_ID2:
			((DatePickerDialog) dialog).updateDate(mYear1, mMonth1, mDay1);break;

		}
		} 
		private void updateDisplay(int id) {
			switch (id) {
			case DATE_DIALOG_ID1 :
				pickDate.setText(
						new StringBuilder()
						// Month is 0 based so add 1
						.append(mDay ).append("-")
						.append(mMonth+1).append("-")
						.append(mYear).append(" "));
			case DATE_DIALOG_ID2:
				pickDate1.setText(
						new StringBuilder()
						 // Month is 0 based so add 1
						.append(mDay1 ).append("-")
						.append(mMonth1+1).append("-")
						.append(mYear1).append(" "));
			}
		
		
		}
		
		private DatePickerDialog.OnDateSetListener mDateSetListener =new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
		mYear = year;
		mMonth = monthOfYear;
		mDay = dayOfMonth;
		updateDisplay(1);
		}


		};
		private DatePickerDialog.OnDateSetListener mDateSetListener1 =new DatePickerDialog.OnDateSetListener() {

			public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
			mYear1 = year;
			mMonth1 = monthOfYear;
			mDay1 = dayOfMonth;
			updateDisplay(2);
			}


			};
			

			public void onClick(View v) {
				if(v == Suivant){
					Intent monIntent = new Intent(this,BonLivraison2.class);
			  	      startActivity(monIntent);}
				else{
		  			
		  			Intent intent=new Intent(this,BonLivraison1.class);
		  			this.startActivityForResult(intent, 1000);
				}
		  			

		
			}
			

			public class LoadDepartements extends AsyncTask<String, String, String>{
				@Override
		          protected void onPreExecute() {
		           super.onPreExecute();
		              pDialog = new ProgressDialog(BonLivraison1.this);
		              pDialog.setMessage("Loading departements. Please wait...");
		              pDialog.setIndeterminate(false);
		              pDialog.setCancelable(true);
		              pDialog.show();
		          }
				 
		          protected String doInBackground(String... arg0) {
		     // Building Parameters
		              List<NameValuePair> params = new ArrayList<NameValuePair>();
		              // getting JSON string from URL
		              JSONObject json = jParser.makeHttpRequest(url_all_departements, "GET", params);
		   
		              // Check your log cat for JSON reponse
		              Log.d("All Departements: ", json.toString());
		              
		              // dismiss the dialog after getting all products
		              try {
		                  // Checking for SUCCESS TAG
		                  int success = json.getInt(TAG_SUCCESS);
		     if (success == 1) {
		                        // products found
		                        // Getting Array of Products
		    	 departements = json.getJSONArray(TAG_depart);
		                        Log.d("aa: ", "qq");
		                        // looping through All Products
		                        for (int i = 0; i < departements.length(); i++) {
		                            JSONObject c = departements.getJSONObject(i);
		     
		                            // Storing each json item in variable
		                            String id = c.getString(TAG_PID);
		                            String name = c.getString(TAG_NAME);
		                            Log.d("aa: ", name);
		                         array_spinner.add(name);
		                         
		     
		                            // creating new HashMap
		                            HashMap<String, String> map = new HashMap<String, String>();
		     
		                            // adding each child node to HashMap key => value
		                            map.put(TAG_PID, id);
		                            map.put(TAG_NAME, name);
		     
		                            // adding HashList to ArrayList
		                            departementList.add(map);
		                        }
		                       
		                    }
		                 
		                  }
		              catch (JSONException e) {
		                  e.printStackTrace();
		              }
		              Log.d("aa: ", "ww");
		              return null;
		          }
		          /**
		           * After completing background task Dismiss the progress dialog
		           * **/
		          protected void onPostExecute(String file_url) {
		              // dismiss the dialog after getting all products
		              pDialog.dismiss();
		              
		              // updating UI from Background Thread
		              runOnUiThread(new Runnable() {
		                  public void run() {
		                      /**
		                       * Updating parsed JSON data into ListView
		                       * */
		                   ListAdapter adapter = new SimpleAdapter(
		                              BonLivraison1.this, departementList,
		                              R.layout.list_item, new String[] { TAG_PID,
		                                      TAG_NAME},
		                              new int[] { R.id.pid, R.id.name });
		                      // updating listview
		                      setListAdapter(adapter);
		                   
		          }

						private void setListAdapter(ListAdapter adapter) {
							// TODO Auto-generated method stub
							
						}
		              });
		              }
		}
		}